<script setup>
import { ref, onMounted } from "vue";
import {
  getDeviceList,
  deleteDeviceInfo,
  getDeviceData,
  uploadMonitorData
} from "@/api/DevConnection";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import AddDialogTable from "./components/AddDialogTable.vue";
import ProtocolConfigDrawer from "./components/ProtocolConfigDrawer.vue";
import CollectSettingDrawer from "./components/CollectSettingDrawer.vue";

onMounted(() => {
  getApiTableDataList();
  // 判断是否为生产环境
  if (process.env.NODE_ENV === "production") {
    getMonitorData();
  }
});

// 将监控数据入湖
const getMonitorData = async () => {
  let monitorData = {
    total_service: 0,
    total_product: 0,
    total_device: 0,
    adaptive_service: 0,
    adaptive_product: 0,
    adaptive_device: 0
  };
  await getDeviceData({ deviceType: null, deviceName: null }).then(res => {
    // 已适配的state为1，未适配未0
    // deviceType为设备、产品、服务
    for (let item of res.data) {
      switch (item["deviceType"]) {
        case "设备":
          monitorData.total_device++;
          break;
        case "产品":
          monitorData.total_service++;
          break;
        case "服务":
          monitorData.total_product++;
          break;
      }
    }
  });
  await getDeviceList().then(res => {
    for (let item of res.data) {
      if (item["state"] == 1) {
        switch (item["deviceType"]) {
          case "设备":
            monitorData.adaptive_device++;
            break;
          case "产品":
            monitorData.adaptive_product++;
            break;
          case "服务":
            monitorData.adaptive_service++;
            break;
        }
      }
    }
  });
  uploadMonitorData(JSON.stringify(monitorData)).then(res => {
    console.log(res);
  });
};

// 协议配置
const protocolConfigDrawer = ref(false);
const devClickProtocolConfig = () => {
  if (!devVarTableSelectedId.value) {
    message("请先选择需要配置的资源", { type: "warning" });
    return;
  }
  protocolConfigDrawer.value = true;
};
// 协议配置抽屉关闭子组件传值
const childProtocolDrawerChange = val => {
  protocolConfigDrawer.value = val;
};

// 采集设置
const collectSettingDrawer = ref(false);
const devClickCollectSetting = () => {
  if (!devVarTableSelectedId.value) {
    message("请先选择需要配置的资源", { type: "warning" });
    return;
  }
  collectSettingDrawer.value = true;
};
// 采集设置抽屉关闭子组件传值
const childCollectDrawerChange = val => {
  collectSettingDrawer.value = val;
};

// 添加按钮,添加设备、产品、服务
const dialogVisible = ref(false);
const devClickAdd = () => {
  dialogVisible.value = true;
};

// 添加资源完成,重新请求资源列表
const childDialogChange = obj => {
  dialogVisible.value = obj.value;
  if (obj.type === "success") {
    getApiTableDataList();
  }
};

// 获取设备、产品、服务列表
const devVarArrTableData = ref([
    {
      type: "",
      fitNum: "",
      itemList: [],
      fitList: []
    },
    {
      type: "",
      fitNum: "",
      itemList: [],
      fitList: []
    },
    {
      type: "",
      fitNum: "",
      itemList: [],
      fitList: []
    }
  ]),
  selectedItemKeys = ref([]);
const getApiTableDataList = () => {
  getDeviceList()
    .then(res => {
      if (res.status === 200) {
        // console.log(res);
        selectedItemKeys.value = res.data;
        devVarArrTableData.value = [
          {
            type: "",
            fitNum: "",
            itemList: [],
            fitList: []
          },
          {
            type: "",
            fitNum: "",
            itemList: [],
            fitList: []
          },
          {
            type: "",
            fitNum: "",
            itemList: [],
            fitList: []
          }
        ];
        for (let i = 0; i < res.data.length; i++) {
          if (
            res.data[i].deviceType === "设备" /*&& res.data[i].isDeleted === 0*/
          ) {
            // devVarObjTableData.value.equipment.push(res.data[i])
            devVarArrTableData.value[0].type = res.data[i].deviceType;
            devVarArrTableData.value[0].itemList.push(res.data[i]);
            if (res.data[i].state === 1) {
              devVarArrTableData.value[0].fitList.push(res.data[i]);
            }
          } else if (
            res.data[i].deviceType === "产品" /*&& res.data[i].isDeleted === 0*/
          ) {
            // devVarObjTableData.value.service.push(res.data[i])
            devVarArrTableData.value[1].type = res.data[i].deviceType;
            devVarArrTableData.value[1].itemList.push(res.data[i]);
            if (res.data[i].state === 1) {
              devVarArrTableData.value[1].fitList.push(res.data[i]);
            }
          } else if (
            res.data[i].deviceType === "服务" /*&& res.data[i].isDeleted === 0*/
          ) {
            // devVarObjTableData.value.production.push(res.data[i])
            devVarArrTableData.value[2].type = res.data[i].deviceType;
            devVarArrTableData.value[2].itemList.push(res.data[i]);
            if (res.data[i].state === 1) {
              devVarArrTableData.value[2].fitList.push(res.data[i]);
            }
          }
          if (devVarTableSelectedId.value === res.data[i].id) {
            devVarTableSelectedItem.value = res.data[i];
          }
        }
      } else {
        message(res.message, { type: "error" });
      }
    })
    .catch(err => {
      console.log(err);
    });
};

// 鼠标点击选中设备、产品、服务以后高亮
const devVarCollectDisabled = ref(false),
  devVarTableSelectedId = ref(null),
  devVarTableSelectedItem = ref(null);
const devClickTableSelected = item => {
  if (devVarTableSelectedId.value && devVarTableSelectedId.value === item.id) {
    devVarTableSelectedId.value = null;
    devVarTableSelectedItem.value = null;

  } else {
    devVarTableSelectedId.value = item.id;
    devVarTableSelectedItem.value = item;
    protocolConfigDrawer.value = true;
  }
  if (item.state === 0) {
    devVarCollectDisabled.value = true;
  } else {
    devVarCollectDisabled.value = false;
  }

  // this.id = selectedItem.id
  // this.deviceType = selectedItem.deviceType
  // this.dev_name = selectedItem.deviceName
  // this.NetId= selectedItem.gatewayId
  // this.port = selectedItem.connector
  // this.getway_id = selectedItem.protocol
  // this.slaveAddress1 = selectedItem.passiveAddress
  // this.slaveip = selectedItem.passiveIp
  // this.portid = selectedItem.passivePort
  // this.m_type  =  selectedItem.protocolType
  // this.addr =  selectedItem.protocolAddress
  // this.num = selectedItem.protocolNumber
  // this.tar_addr = selectedItem.targetAddress
  // this.tar_port = selectedItem.targetPort
  // this.device_account = selectedItem.deviceAccount
  // this.device_pwd = selectedItem.devicePassword
  // this.clientId = selectedItem.clientId
  // this.sub_topic = selectedItem.subscribeTopic
  // this.issue_topic = selectedItem.releaseTopic
  // this.qos = selectedItem.qos
  // this.cls = selectedItem.clearSession
  // this.URL = selectedItem.url
  // this.securityPolicy = selectedItem.securityPolicy
  // this.file = selectedItem.nodePath
  // this.password = selectedItem.certificates
  // this.dataReading = selectedItem.readingMethod
  // this.timeout = selectedItem.timeoutSetting
  // this.RSbaud =selectedItem.baudRate
  // this.RSdataBit = selectedItem.dataBit
  // this.RSstopBit = selectedItem.stopBit
  // this.RSschool = selectedItem.verify
  // this.CANZformat = selectedItem.frameFormat
  // this.CANZtype =  selectedItem.frameType
  // this.CANZid = selectedItem.frameId
  // this.WIFIid = selectedItem.wifiAccount
  // this.WIFIpassword = selectedItem.wifiPassword
};

// 删除设备、产品、服务
const devClickTableDelete = item => {
  ElMessageBox.confirm("确定要删除吗?", { type: "warning" })
    .then(() => {
      deleteDeviceInfo({ id: item.id })
        .then(res => {
          if (res.status === 200) {
            getApiTableDataList();
            message("删除成功！", { type: "success" });
          } else {
            message(res.message, { type: "error" });
          }
        })
        .catch(err => {
          console.log(err);
        });
    })
    .catch(() => {
      // catch error
    });
};
</script>

<template>
  <div class="dev-wrapper">
    <div class="dev-header">
      <div class="dev-header-left">
        <!-- <el-button type="primary"@click="devClickProtocolConfig">协议配置</el-button> -->
        <el-button
        type="primary"
          :disabled="devVarCollectDisabled"
          @click="devClickCollectSetting"
          >采集设置</el-button
        >
      </div>
      <el-button type="primary" @click="devClickAdd">添 加</el-button>
    </div>
    <div class="dev-body-main">
      <!-- 设备、产品、服务 -->
      <div
        v-for="tableList in devVarArrTableData"
        :key="tableList"
        class="dev-body-item"
      >
        <div class="dev-body-title">
          <h3 class="dev-body-text">{{ tableList.type }}</h3>
          <span class="dev-body-tips"
            >接入{{ tableList.itemList.length }}个，适配{{
              tableList.fitList.length
            }}个</span
          >
        </div>
        <div class="dev-body-table">
          <div
            v-for="item in tableList.itemList"
            :key="item"
            class="table-block-box"
            :class="[
              item.id === devVarTableSelectedId ? 'table-selected-active' : '',
              item.state === 1 ? 'table-shadow-green' : '',
              item.state === 0 ? 'table-shadow-red' : ''
            ]"
          >
            <div class="table-block" @click="devClickTableSelected(item)">
              <div class="table-block-title">
                <div class="table-block-text">{{ item.deviceName }}</div>
                <el-button
                  class="table-block-del"
                  link
                  type="primary"
                  @click.stop="devClickTableDelete(item)"
                  >删除</el-button
                >
              </div>
              <div class="table-block-status">
                设备状态：{{ item.state === 0 ? "未适配" : "已适配" }}
              </div>
              <div class="table-block-id">网关ID:{{ item.gatewayId }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 协议配置 -->
    <ProtocolConfigDrawer
      :protocolConfig-drawer="protocolConfigDrawer"
      :devVarTableSelected-item="devVarTableSelectedItem"
      @childProtocolDrawer="childProtocolDrawerChange"
      @childGetApiTableDataList="getApiTableDataList"
    />
    <!-- 采集设置 -->
    <CollectSettingDrawer
      :collectSetting-drawer="collectSettingDrawer"
      :devVarTableSelected-item="devVarTableSelectedItem"
      @childCollectDrawer="childCollectDrawerChange"
    />
    <!-- 添加资源设备、产品、服务 -->
    <AddDialogTable
      :dialog-visible="dialogVisible"
      :selected-itemKeys="selectedItemKeys"
      @childDialogVisible="childDialogChange"
    />
  </div>
</template>

<style>
.dev-body-main::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
  border-radius: 8px;
  background-color: #f5f5f5;
}

.dev-body-main::-webkit-scrollbar {
  width: 8px;
  background-color: #f5f5f5;
}

.dev-body-main::-webkit-scrollbar-thumb {
  border-radius: 8px;
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
  background-color: #8b8b8b;
}

.dev-body-table::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
  border-radius: 8px;
  background-color: #f5f5f5;
}

.dev-body-table::-webkit-scrollbar {
  width: 8px;
  background-color: #f5f5f5;
}

.dev-body-table::-webkit-scrollbar-thumb {
  border-radius: 8px;
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
  background-color: #8b8b8b;
}
</style>

<style lang="scss" scoped>
.dev-wrapper {
  width: 100%;
  height: 100%;
  font-size: 16px;
  font-weight: 500;
  border-radius: 10px;
  box-shadow: 2px 2px 2px 1px rgba(0, 0, 0, 0.2);
  background-color: #fff;

  .dev-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 15px 10px 10px;
  }

  .dev-body-main {
    height: calc(100% - 57px);
    overflow: auto;

    .dev-body-item {
      width: 100%;
      /* height: calc(30% - 30px); */
      .dev-body-title {
        .dev-body-text {
          display: inline-block;
          padding: 0 15px;
        }
      }

      .dev-body-table {
        width: 100%;
        // max-height: 232px;
        display: flex;
        /* height: calc(100% - 30px); */
        flex-wrap: wrap;
        // overflow: auto;
        margin-top: 10px;

        .table-block-box {
          width: 270px;
          /* height: 140px; */
          border-right: 1px solid #ccc;
          background-color: #fff;
          border-radius: 10px;
          margin: 10px;
          flex-basis: calc(20% - 20px);
          vertical-align: top;

          .table-block {
            padding-left: 14px;
            border-radius: 10px;
            box-shadow: 2px 2px 2px 2px rgba(0, 0, 0, 0.2);

            .table-block-title {
              display: flex;
              justify-content: space-between;
              padding: 10px 14px 0 0;

              .table-block-text {
                display: inline-block;
                font-weight: 700;
                white-space: nowrap; /* 文本不换行 */
                overflow: hidden; /* 超出部分隐藏 */
                text-overflow: ellipsis; /* 显示省略号 */
              }
            }

            .table-block-status {
              margin: 6px 0;
              font-size: 14px;
              color: gray;
            }

            .table-block-id {
              font-size: 14px;
              color: gray;
              padding-bottom: 8px;
            }
          }
        }

        .table-selected-active {
          background-color: #efecec;
          cursor: pointer;
          /* 设置鼠标样式为手型 */
        }

        .table-shadow-green {
          box-shadow: 0px -9px 1px -3px #6fc444;
        }

        .table-shadow-red {
          box-shadow: 0px -9px 1px -3px red;
        }
      }
    }
  }
}
</style>
